All files / api database.ts

91.17% Statements 630/691
81.17% Branches 194/239
92.91% Functions 118/127
91.13% Lines 596/654
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933                                        2x 2x   2x 2x                     2x 2x 2x 2x             2x 2x 2x 2x 2x 2x 2x 2x 2x                           2x 2x 2x 2x     2x             2x               2x                     2x 2x                                           2x                       873x 437x 2x         435x 435x   436x 434x   434x 434x   869x   867x           867x     2x 2x           2x   2x             2x         2x                           433x       433x 433x 433x     432x 432x 432x 432x 432x   1x 1x             1x   1x 1x     433x 433x 433x     2x 440x 440x   440x                   440x 434x 2x               432x 432x             2x 14x 14x     2x 12x 12x     2x 218x 2x               216x     2x 1682x 215x   1682x     431x 431x         431x   431x             431x 2014x 32x 32x 32x 12x             20x   1982x     431x   431x           431x     2x 432x 432x                               432x                   432x 432x           432x     2x                     433x   432x 430x         2x 532x 532x 530x             530x 530x     2x 106x 106x 104x           104x 104x     132x     132x 132x 130x   192x         2x 124x   124x     2x 2x       2x               2x                                       2x         2x   192x 192x     86x     86x 86x         84x     80x     80x 80x 4x   76x       2x         96x 96x         94x 94x     56x 56x                         2x       96x         96x       2x 2x         2x             94x 94x         92x           32x 28x     2x 18x 18x         16x 16x   2x   2x 124x 124x   124x   2x         60x 60x 60x         58x 58x     20x     20x                         2x       72x   72x         72x       2x 2x         2x             70x 70x         68x           8x     8x     2x 6x 6x 6x         4x     4x     2x 22x 22x 22x 20x       2x 160x               2x         2x     648x 648x     2x 636x 8x             628x     2x 88x     2x 2x     2x 10x     2x 20x 18x 16x           16x 10x     2x 16x     16x     2x       422x 422x   422x                 372x                     2x     110x       110x       20x 18x             90x 90x           36x         2x 2x 2x                                               50x 40x           40x       40x 40x       10x 10x     8x           8x     38x         38x     38x           38x           38x           38x           38x     162x       162x     162x 124x     162x   218x 218x       218x   218x                       162x           162x 158x 158x       124x 124x 124x   124x                   124x   124x                             124x                 2x   2x   222x 222x     2x 12x         2x         2x   2178x 2178x 2178x 2178x     2x     378x 378x 376x               2x       76x 76x 74x 72x     52x 44x           10x     2x 10x     2x       2x 256x     2x 76x           2x 12x     12x                   482x       482x 482x 826x   482x     2x 884x 108x 776x 8x 768x 12x 12x 12x                         12x   756x       8x 8x 14x     2x   2x                     2x 218x 218x       218x   2x   2x 748x   2x         118x 118x 118x   118x 98x 18x 10x   2x             8x 2x             6x 6x 6x       8x 6x 6x   2x                 80x         92x         88x 82x     2x       106x 106x   106x 98x 8x 8x               106x 4x           102x 4x           98x 78x 78x 74x     2x 18x 18x 18x 4x           14x     2x   20x   20x 20x           10x     2x   12x   12x 12x           10x     2x   12x   12x 12x           10x     2x   6x   6x 6x           4x     2x 14x     14x           2x           50x 50x 18x           18x 18x             18x   32x 32x                           2x         18x                 22x 22x 10x   12x 12x 4x   8x 8x                 10x           2x           32x 32x 4x               28x 28x 28x 28x 28x 8x 2x           6x 2x           4x 4x   20x       20x       24x                                       40x 24x 24x   24x 24x       16x 16x       14x           14x           14x     22x     22x 22x           22x           22x           22x     88x       88x     88x 66x     88x   124x 124x           88x 88x         88x 88x 88x       66x 66x 66x   66x                   66x   66x                 2x 88x 64x 64x 2x                 62x 62x 12x         2x 78x   64x 64x 14x         2x       26x 8x                   2x   2x 146x         146x 146x 146x   146x           2x 142x 280x 142x     2x 10x     2x 4x     142x       142x 142x 142x 280x       2x       2x                     2x 14x       14x             2x 280x             2x   2x     540x 540x 8x                 2x       2x 6x 6x 2x   4x       2x 8x     2x 550x     548x 282x   548x 544x           544x 538x           2x 2x 2x 2x 2x   2x           574x 560x         14x 14x 14x             454x 434x     20x 18x             16x               434x   434x 14x         420x                 2x       104x                                                             104x 104x 1584x           1584x 1584x 1584x 375x 375x 375x   1584x 1485x 1485x   1584x           1584x   1209x     276x   99x                       2x       2x       2x       2x       2x 2x     2x 2x 2x          
/**
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
import * as firestore from '@firebase/firestore-types';
 
import { FirebaseApp } from '@firebase/app-types';
import { FirebaseService } from '@firebase/app-types/private';
import { FieldPath as ExternalFieldPath } from './field_path';
import { DatabaseId, DatabaseInfo } from '../core/database_info';
import { ListenOptions } from '../core/event_manager';
import { FirestoreClient } from '../core/firestore_client';
import {
  Bound,
  Direction,
  fieldFilter,
  Filter,
  OrderBy,
  Query as InternalQuery,
  RelationFilter,
  RelationOp
} from '../core/query';
import { Transaction as InternalTransaction } from '../core/transaction';
import { ChangeType, ViewSnapshot } from '../core/view_snapshot';
import { Document, MaybeDocument, NoDocument } from '../model/document';
import { DocumentKey } from '../model/document_key';
import {
  ArrayValue,
  FieldValue,
  FieldValueOptions,
  ObjectValue,
  RefValue
} from '../model/field_value';
import { DeleteMutation, Mutation, Precondition } from '../model/mutation';
import { FieldPath, ResourcePath } from '../model/path';
import { PlatformSupport } from '../platform/platform';
import { makeConstructorPrivate } from '../util/api';
import { assert, fail } from '../util/assert';
import { AsyncObserver } from '../util/async_observer';
import { AsyncQueue } from '../util/async_queue';
import { Code, FirestoreError } from '../util/error';
import {
  invalidClassError,
  validateArgType,
  validateAtLeastNumberOfArgs,
  validateBetweenNumberOfArgs,
  validateDefined,
  validateExactNumberOfArgs,
  validateNamedOptionalType,
  validateNamedOptionalPropertyEquals,
  validateNamedType,
  validateOptionalArgType,
  validateOptionNames,
  valueDescription
} from '../util/input_validation';
import * as log from '../util/log';
import { LogLevel } from '../util/log';
import { AnyJs, AutoId } from '../util/misc';
import * as objUtils from '../util/obj';
import { Rejecter, Resolver } from '../util/promise';
 
import {
  CredentialsProvider,
  CredentialsSettings,
  EmptyCredentialsProvider,
  FirebaseCredentialsProvider,
  makeCredentialsProvider
} from './credentials';
import {
  CompleteFn,
  ErrorFn,
  isPartialObserver,
  NextFn,
  PartialObserver,
  Unsubscribe
} from './observer';
import {
  DocumentKeyReference,
  fieldPathFromArgument,
  UserDataConverter
} from './user_data_converter';
 
// The objects that are a part of this API are exposed to third-parties as
// compiled javascript so we want to flag our private members with a leading
// underscore to discourage their use.
// tslint:disable:strip-private-property-underscore
 
const DEFAULT_HOST = 'firestore.googleapis.com';
const DEFAULT_SSL = true;
 
/** Undocumented, private additional settings not exposed in our public API. */
interface PrivateSettings extends firestore.Settings {
  // Can be a google-auth-library or gapi client.
  credentials?: CredentialsSettings;
}
 
/**
 * Options that can be provided in the Firestore constructor when not using
 * Firebase (aka standalone mode).
 */
export interface FirestoreDatabase {
  projectId: string;
  database?: string;
}
 
/**
 * A concrete type describing all the values that can be applied via a
 * user-supplied firestore.Settings object. This is a separate type so that
 * defaults can be supplied and the value can be checked for equality.
 */
class FirestoreSettings {
  /** The hostname to connect to. */
  host: string;
 
  /** Whether to use SSL when connecting. */
  ssl: boolean;
 
  // Can be a google-auth-library or gapi client.
  // tslint:disable-next-line:no-any
  credentials?: any;
 
  constructor(settings: PrivateSettings) {
    if (settings.host === undefined) {
      if (settings.ssl !== undefined) {
        throw new FirestoreError(
          Code.INVALID_ARGUMENT,
          "Can't provide ssl option if host option is not set"
        );
      }
      this.host = DEFAULT_HOST;
      this.ssl = DEFAULT_SSL;
    } else {
      validateNamedType('settings', 'string', 'host', settings.host);
      this.host = settings.host;
 
      validateNamedOptionalType('settings', 'boolean', 'ssl', settings.ssl);
      this.ssl = objUtils.defaulted(settings.ssl, DEFAULT_SSL);
    }
    validateOptionNames('settings', settings, ['host', 'ssl', 'credentials']);
 
    validateNamedOptionalType(
      'settings',
      'object',
      'credentials',
      settings.credentials
    );
    this.credentials = settings.credentials;
  }
 
  isEqual(other: FirestoreSettings): boolean {
    return (
      this.host === other.host &&
      this.ssl === other.ssl &&
      this.credentials === other.credentials
    );
  }
}
 
class FirestoreConfig {
  databaseId: DatabaseId;
  persistenceKey: string;
  credentials: CredentialsProvider;
  firebaseApp: FirebaseApp;
  settings: FirestoreSettings;
  persistence: boolean;
}
 
/**
 * The root reference to the database.
 */
export class Firestore implements firestore.FirebaseFirestore, FirebaseService {
  private readonly _config: FirestoreConfig;
  readonly _databaseId: DatabaseId;
 
  // The firestore client instance. This will be available as soon as
  // configureClient is called, but any calls against it will block until
  // setup has completed.
  //
  // Operations on the _firestoreClient don't block on _firestoreReady. Those
  // are already set to synchronize on the async queue.
  private _firestoreClient: FirestoreClient | undefined;
 
  // Public for use in tests.
  // TODO(mikelehen): Use modularized initialization instead.
  readonly _queue = new AsyncQueue();
 
  _dataConverter: UserDataConverter;
 
  constructor(databaseIdOrApp: FirestoreDatabase | FirebaseApp) {
    const config = new FirestoreConfig();
    if (typeof (databaseIdOrApp as FirebaseApp).options === 'object') {
      // This is very likely a Firebase app object
      // TODO(b/34177605): Can we somehow use instanceof?
      const app = databaseIdOrApp as FirebaseApp;
      config.firebaseApp = app;
      config.databaseId = Firestore.databaseIdFromApp(app);
      config.persistenceKey = config.firebaseApp.name;
      config.credentials = new FirebaseCredentialsProvider(app);
    } else {
      const external = databaseIdOrApp as FirestoreDatabase;
      Iif (!external.projectId) {
        throw new FirestoreError(
          Code.INVALID_ARGUMENT,
          'Must provide projectId'
        );
      }
 
      config.databaseId = new DatabaseId(external.projectId, external.database);
      // Use a default persistenceKey that lines up with FirebaseApp.
      config.persistenceKey = '[DEFAULT]';
      config.credentials = new EmptyCredentialsProvider();
    }
 
    config.settings = new FirestoreSettings({});
    this._config = config;
    this._databaseId = config.databaseId;
  }
 
  settings(settingsLiteral: firestore.Settings): void {
    validateExactNumberOfArgs('Firestore.settings', arguments, 1);
    validateArgType('Firestore.settings', 'object', 1, settingsLiteral);
 
    Iif (
      objUtils.contains(settingsLiteral as objUtils.Dict<{}>, 'persistence')
    ) {
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        '"persistence" is now specified with a separate call to ' +
          'firestore.enablePersistence().'
      );
    }
 
    const newSettings = new FirestoreSettings(settingsLiteral);
    if (this._firestoreClient && !this._config.settings.isEqual(newSettings)) {
      throw new FirestoreError(
        Code.FAILED_PRECONDITION,
        'Firestore has already been started and its settings can no longer ' +
          'be changed. You can only call settings() before calling any other ' +
          'methods on a Firestore object.'
      );
    }
 
    this._config.settings = newSettings;
    Iif (newSettings.credentials !== undefined) {
      this._config.credentials = makeCredentialsProvider(
        newSettings.credentials
      );
    }
  }
 
  enableNetwork(): Promise<void> {
    this.ensureClientConfigured();
    return this._firestoreClient.enableNetwork();
  }
 
  disableNetwork(): Promise<void> {
    this.ensureClientConfigured();
    return this._firestoreClient.disableNetwork();
  }
 
  enablePersistence(): Promise<void> {
    if (this._firestoreClient) {
      throw new FirestoreError(
        Code.FAILED_PRECONDITION,
        'Firestore has already been started and persistence can no longer ' +
          'be enabled. You can only call enablePersistence() before calling ' +
          'any other methods on a Firestore object.'
      );
    }
 
    return this.configureClient(/* persistence= */ true);
  }
 
  ensureClientConfigured(): FirestoreClient {
    if (!this._firestoreClient) {
      this.configureClient(/* persistence= */ false);
    }
    return this._firestoreClient as FirestoreClient;
  }
 
  private configureClient(persistence: boolean): Promise<void> {
    assert(
      !!this._config.settings.host,
      'FirestoreSettings.host cannot be falsey'
    );
 
    assert(!this._firestoreClient, 'configureClient() called multiple times');
 
    const databaseInfo = new DatabaseInfo(
      this._config.databaseId,
      this._config.persistenceKey,
      this._config.settings.host,
      this._config.settings.ssl
    );
 
    const preConverter = (value: AnyJs) => {
      if (value instanceof DocumentReference) {
        const thisDb = this._config.databaseId;
        const otherDb = value.firestore._config.databaseId;
        if (!otherDb.isEqual(thisDb)) {
          throw new FirestoreError(
            Code.INVALID_ARGUMENT,
            'Document reference is for database ' +
              `${otherDb.projectId}/${otherDb.database} but should be ` +
              `for database ${thisDb.projectId}/${thisDb.database}`
          );
        }
        return new DocumentKeyReference(this._config.databaseId, value._key);
      } else {
        return value;
      }
    };
    this._dataConverter = new UserDataConverter(preConverter);
 
    this._firestoreClient = new FirestoreClient(
      PlatformSupport.getPlatform(),
      databaseInfo,
      this._config.credentials,
      this._queue
    );
    return this._firestoreClient.start(persistence);
  }
 
  private static databaseIdFromApp(app: FirebaseApp): DatabaseId {
    const options = app.options as objUtils.Dict<{}>;
    Iif (!objUtils.contains(options, 'projectId')) {
      // TODO(b/62673263): We can safely remove the special handling of
      // 'firestoreId' once alpha testers have upgraded.
      if (objUtils.contains(options, 'firestoreId')) {
        throw new FirestoreError(
          Code.INVALID_ARGUMENT,
          '"firestoreId" is now specified as "projectId" in ' +
            'firebase.initializeApp.'
        );
      }
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        '"projectId" not provided in firebase.initializeApp.'
      );
    }
 
    Iif (objUtils.contains(options, 'firestoreOptions')) {
      // TODO(b/62673263): We can safely remove the special handling of
      // 'firestoreOptions' once alpha testers have upgraded.
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        '"firestoreOptions" values are now specified with ' +
          'Firestore.settings()'
      );
    }
 
    const projectId = options['projectId'];
    Iif (!projectId || typeof projectId !== 'string') {
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        'projectId must be a string in FirebaseApp.options'
      );
    }
    return new DatabaseId(projectId);
  }
 
  get app(): FirebaseApp {
    if (!this._config.firebaseApp) {
      throw new FirestoreError(
        Code.FAILED_PRECONDITION,
        "Firestore was not initialized using the Firebase SDK. 'app' is " +
          'not available'
      );
    }
    return this._config.firebaseApp;
  }
 
  INTERNAL = {
    delete: async (): Promise<void> => {
      if (this._firestoreClient) {
        return this._firestoreClient.shutdown();
      }
    }
  };
 
  collection(pathString: string): firestore.CollectionReference {
    validateExactNumberOfArgs('Firestore.collection', arguments, 1);
    validateArgType('Firestore.collection', 'string', 1, pathString);
    Iif (!pathString) {
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        'Must provide a non-empty collection path to collection()'
      );
    }
 
    this.ensureClientConfigured();
    return new CollectionReference(ResourcePath.fromString(pathString), this);
  }
 
  doc(pathString: string): firestore.DocumentReference {
    validateExactNumberOfArgs('Firestore.doc', arguments, 1);
    validateArgType('Firestore.doc', 'string', 1, pathString);
    Iif (!pathString) {
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        'Must provide a non-empty document path to doc()'
      );
    }
    this.ensureClientConfigured();
    return DocumentReference.forPath(ResourcePath.fromString(pathString), this);
  }
 
  runTransaction<T>(
    updateFunction: (transaction: firestore.Transaction) => Promise<T>
  ): Promise<T> {
    validateExactNumberOfArgs('Firestore.runTransaction', arguments, 1);
    validateArgType('Firestore.runTransaction', 'function', 1, updateFunction);
    return this.ensureClientConfigured().transaction(
      (transaction: InternalTransaction) => {
        return updateFunction(new Transaction(this, transaction));
      }
    );
  }
 
  batch(): firestore.WriteBatch {
    this.ensureClientConfigured();
 
    return new WriteBatch(this);
  }
 
  static get logLevel(): firestore.LogLevel {
    switch (log.getLogLevel()) {
      case LogLevel.DEBUG:
        return 'debug';
      case LogLevel.ERROR:
        return 'error';
      case LogLevel.SILENT:
        return 'silent';
      default:
        return fail('Unknown log level: ' + log.getLogLevel());
    }
  }
 
  static setLogLevel(level: firestore.LogLevel) {
    validateExactNumberOfArgs('Firestore.setLogLevel', arguments, 1);
    validateArgType('Firestore.setLogLevel', 'string', 1, level);
    switch (level) {
      case 'debug':
        log.setLogLevel(log.LogLevel.DEBUG);
        break;
      case 'error':
        log.setLogLevel(log.LogLevel.ERROR);
        break;
      case 'silent':
        log.setLogLevel(log.LogLevel.SILENT);
        break;
      default:
        throw new FirestoreError(
          Code.INVALID_ARGUMENT,
          'Invalid log level: ' + level
        );
    }
  }
}
 
/**
 * A reference to a transaction.
 */
export class Transaction implements firestore.Transaction {
  constructor(
    private _firestore: Firestore,
    private _transaction: InternalTransaction
  ) {}
 
  get(
    documentRef: firestore.DocumentReference
  ): Promise<firestore.DocumentSnapshot> {
    validateExactNumberOfArgs('Transaction.get', arguments, 1);
    const ref = validateReference(
      'Transaction.get',
      documentRef,
      this._firestore
    );
    return this._transaction
      .lookup([ref._key])
      .then((docs: MaybeDocument[]) => {
        Iif (!docs || docs.length !== 1) {
          return fail('Mismatch in docs returned from document lookup.');
        }
        const doc = docs[0];
        if (doc instanceof NoDocument) {
          return new DocumentSnapshot(this._firestore, ref._key, null, false);
        }
        return new DocumentSnapshot(this._firestore, ref._key, doc, false);
      });
  }
 
  set(
    documentRef: firestore.DocumentReference,
    value: firestore.DocumentData,
    options?: firestore.SetOptions
  ): Transaction {
    validateBetweenNumberOfArgs('Transaction.set', arguments, 2, 3);
    const ref = validateReference(
      'Transaction.set',
      documentRef,
      this._firestore
    );
    options = validateSetOptions('Transaction.set', options);
    const parsed = options.merge
      ? this._firestore._dataConverter.parseMergeData('Transaction.set', value)
      : this._firestore._dataConverter.parseSetData('Transaction.set', value);
    this._transaction.set(ref._key, parsed);
    return this;
  }
 
  update(
    documentRef: firestore.DocumentReference,
    value: firestore.UpdateData
  ): Transaction;
  update(
    documentRef: firestore.DocumentReference,
    field: string | ExternalFieldPath,
    value: AnyJs,
    ...moreFieldsAndValues: AnyJs[]
  ): Transaction;
  update(
    documentRef: firestore.DocumentReference,
    fieldOrUpdateData: string | ExternalFieldPath | firestore.UpdateData,
    value?: AnyJs,
    ...moreFieldsAndValues: AnyJs[]
  ): Transaction {
    let ref;
    let parsed;
 
    if (
      typeof fieldOrUpdateData === 'string' ||
      fieldOrUpdateData instanceof ExternalFieldPath
    ) {
      validateAtLeastNumberOfArgs('Transaction.update', arguments, 3);
      ref = validateReference(
        'Transaction.update',
        documentRef,
        this._firestore
      );
      parsed = this._firestore._dataConverter.parseUpdateVarargs(
        'Transaction.update',
        fieldOrUpdateData,
        value,
        moreFieldsAndValues
      );
    } else {
      validateExactNumberOfArgs('Transaction.update', arguments, 2);
      ref = validateReference(
        'Transaction.update',
        documentRef,
        this._firestore
      );
      parsed = this._firestore._dataConverter.parseUpdateData(
        'Transaction.update',
        fieldOrUpdateData
      );
    }
 
    this._transaction.update(ref._key, parsed);
    return this;
  }
 
  delete(documentRef: firestore.DocumentReference): Transaction {
    validateExactNumberOfArgs('Transaction.delete', arguments, 1);
    const ref = validateReference(
      'Transaction.delete',
      documentRef,
      this._firestore
    );
    this._transaction.delete(ref._key);
    return this;
  }
}
 
export class WriteBatch implements firestore.WriteBatch {
  private _mutations = [] as Mutation[];
  private _committed = false;
 
  constructor(private _firestore: Firestore) {}
 
  set(
    documentRef: firestore.DocumentReference,
    value: firestore.DocumentData,
    options?: firestore.SetOptions
  ): WriteBatch {
    validateBetweenNumberOfArgs('WriteBatch.set', arguments, 2, 3);
    this.verifyNotCommitted();
    const ref = validateReference(
      'WriteBatch.set',
      documentRef,
      this._firestore
    );
    options = validateSetOptions('WriteBatch.set', options);
    const parsed = options.merge
      ? this._firestore._dataConverter.parseMergeData('WriteBatch.set', value)
      : this._firestore._dataConverter.parseSetData('WriteBatch.set', value);
    this._mutations = this._mutations.concat(
      parsed.toMutations(ref._key, Precondition.NONE)
    );
    return this;
  }
 
  update(
    documentRef: firestore.DocumentReference,
    value: firestore.UpdateData
  ): WriteBatch;
  update(
    documentRef: firestore.DocumentReference,
    field: string | ExternalFieldPath,
    value: AnyJs,
    ...moreFieldsAndValues: AnyJs[]
  ): WriteBatch;
  update(
    documentRef: firestore.DocumentReference,
    fieldOrUpdateData: string | ExternalFieldPath | firestore.UpdateData,
    value?: AnyJs,
    ...moreFieldsAndValues: AnyJs[]
  ): WriteBatch {
    this.verifyNotCommitted();
 
    let ref;
    let parsed;
 
    if (
      typeof fieldOrUpdateData === 'string' ||
      fieldOrUpdateData instanceof ExternalFieldPath
    ) {
      validateAtLeastNumberOfArgs('WriteBatch.update', arguments, 3);
      ref = validateReference(
        'WriteBatch.update',
        documentRef,
        this._firestore
      );
      parsed = this._firestore._dataConverter.parseUpdateVarargs(
        'WriteBatch.update',
        fieldOrUpdateData,
        value,
        moreFieldsAndValues
      );
    } else {
      validateExactNumberOfArgs('WriteBatch.update', arguments, 2);
      ref = validateReference(
        'WriteBatch.update',
        documentRef,
        this._firestore
      );
      parsed = this._firestore._dataConverter.parseUpdateData(
        'WriteBatch.update',
        fieldOrUpdateData
      );
    }
 
    this._mutations = this._mutations.concat(
      parsed.toMutations(ref._key, Precondition.exists(true))
    );
    return this;
  }
 
  delete(documentRef: firestore.DocumentReference): WriteBatch {
    validateExactNumberOfArgs('WriteBatch.delete', arguments, 1);
    this.verifyNotCommitted();
    const ref = validateReference(
      'WriteBatch.delete',
      documentRef,
      this._firestore
    );
    this._mutations = this._mutations.concat(
      new DeleteMutation(ref._key, Precondition.NONE)
    );
    return this;
  }
 
  async commit(): Promise<void> {
    this.verifyNotCommitted();
    this._committed = true;
    if (this._mutations.length > 0) {
      return this._firestore.ensureClientConfigured().write(this._mutations);
    }
  }
 
  private verifyNotCommitted() {
    Iif (this._committed) {
      throw new FirestoreError(
        Code.FAILED_PRECONDITION,
        'A write batch can no longer be used after commit() ' +
          'has been called.'
      );
    }
  }
}
 
/**
 * A reference to a particular document in a collection in the database.
 */
export class DocumentReference implements firestore.DocumentReference {
  private _firestoreClient: FirestoreClient;
 
  constructor(public _key: DocumentKey, readonly firestore: Firestore) {
    this._firestoreClient = this.firestore.ensureClientConfigured();
  }
 
  static forPath(path: ResourcePath, firestore: Firestore) {
    if (path.length % 2 !== 0) {
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        'Invalid document reference. Document ' +
          'references must have an even number of segments, but ' +
          `${path.canonicalString()} has ${path.length}`
      );
    }
    return new DocumentReference(new DocumentKey(path), firestore);
  }
 
  get id(): string {
    return this._key.path.lastSegment();
  }
 
  get parent(): firestore.CollectionReference {
    return new CollectionReference(this._key.path.popLast(), this.firestore);
  }
 
  get path(): string {
    return this._key.path.canonicalString();
  }
 
  collection(pathString: string): firestore.CollectionReference {
    validateExactNumberOfArgs('DocumentReference.collection', arguments, 1);
    validateArgType('DocumentReference.collection', 'string', 1, pathString);
    Iif (!pathString) {
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        'Must provide a non-empty collection name to collection()'
      );
    }
    const path = ResourcePath.fromString(pathString);
    return new CollectionReference(this._key.path.child(path), this.firestore);
  }
 
  isEqual(other: firestore.DocumentReference): boolean {
    Iif (!(other instanceof DocumentReference)) {
      throw invalidClassError('isEqual', 'DocumentReference', 1, other);
    }
    return this.firestore === other.firestore && this._key.isEqual(other._key);
  }
 
  set(
    value: firestore.DocumentData,
    options?: firestore.SetOptions
  ): Promise<void> {
    validateBetweenNumberOfArgs('DocumentReference.set', arguments, 1, 2);
    options = validateSetOptions('DocumentReference.set', options);
 
    const parsed = options.merge
      ? this.firestore._dataConverter.parseMergeData(
          'DocumentReference.set',
          value
        )
      : this.firestore._dataConverter.parseSetData(
          'DocumentReference.set',
          value
        );
    return this._firestoreClient.write(
      parsed.toMutations(this._key, Precondition.NONE)
    );
  }
 
  update(value: firestore.UpdateData): Promise<void>;
  update(
    field: string | ExternalFieldPath,
    value: AnyJs,
    ...moreFieldsAndValues: AnyJs[]
  ): Promise<void>;
  update(
    fieldOrUpdateData: string | ExternalFieldPath | firestore.UpdateData,
    value?: AnyJs,
    ...moreFieldsAndValues: AnyJs[]
  ): Promise<void> {
    let parsed;
 
    if (
      typeof fieldOrUpdateData === 'string' ||
      fieldOrUpdateData instanceof ExternalFieldPath
    ) {
      validateAtLeastNumberOfArgs('DocumentReference.update', arguments, 2);
      parsed = this.firestore._dataConverter.parseUpdateVarargs(
        'DocumentReference.update',
        fieldOrUpdateData,
        value,
        moreFieldsAndValues
      );
    } else {
      validateExactNumberOfArgs('DocumentReference.update', arguments, 1);
      parsed = this.firestore._dataConverter.parseUpdateData(
        'DocumentReference.update',
        fieldOrUpdateData
      );
    }
 
    return this._firestoreClient.write(
      parsed.toMutations(this._key, Precondition.exists(true))
    );
  }
 
  delete(): Promise<void> {
    validateExactNumberOfArgs('DocumentReference.delete', arguments, 0);
    return this._firestoreClient.write([
      new DeleteMutation(this._key, Precondition.NONE)
    ]);
  }
 
  onSnapshot(
    observer: PartialObserver<firestore.DocumentSnapshot>
  ): Unsubscribe;
  onSnapshot(
    options: firestore.DocumentListenOptions,
    observer: PartialObserver<firestore.DocumentSnapshot>
  ): Unsubscribe;
  onSnapshot(
    onNext: NextFn<firestore.DocumentSnapshot>,
    onError?: ErrorFn,
    onCompletion?: CompleteFn
  ): Unsubscribe;
  onSnapshot(
    options: firestore.DocumentListenOptions,
    onNext: NextFn<firestore.DocumentSnapshot>,
    onError?: ErrorFn,
    onCompletion?: CompleteFn
  ): Unsubscribe;
 
  onSnapshot(...args: AnyJs[]): Unsubscribe {
    validateBetweenNumberOfArgs(
      'DocumentReference.onSnapshot',
      arguments,
      1,
      4
    );
    let options: firestore.DocumentListenOptions = {
      includeMetadataChanges: false
    };
    let observer: PartialObserver<firestore.DocumentSnapshot>;
    let currArg = 0;
    if (
      typeof args[currArg] === 'object' &&
      !isPartialObserver(args[currArg])
    ) {
      options = args[currArg] as firestore.DocumentListenOptions;
      validateOptionNames('DocumentReference.onSnapshot', options, [
        'includeMetadataChanges'
      ]);
      validateNamedOptionalType(
        'DocumentReference.onSnapshot',
        'boolean',
        'includeMetadataChanges',
        options.includeMetadataChanges
      );
      currArg++;
    }
 
    const internalOptions = {
      includeDocumentMetadataChanges: options.includeMetadataChanges,
      includeQueryMetadataChanges: options.includeMetadataChanges
    };
 
    Iif (isPartialObserver(args[currArg])) {
      observer = args[currArg] as PartialObserver<firestore.DocumentSnapshot>;
    } else {
      validateArgType(
        'DocumentReference.onSnapshot',
        'function',
        currArg,
        args[currArg]
      );
      validateOptionalArgType(
        'DocumentReference.onSnapshot',
        'function',
        currArg + 1,
        args[currArg + 1]
      );
      validateOptionalArgType(
        'DocumentReference.onSnapshot',
        'function',
        currArg + 2,
        args[currArg + 2]
      );
      observer = {
        next: args[currArg] as NextFn<firestore.DocumentSnapshot>,
        error: args[currArg + 1] as ErrorFn,
        complete: args[currArg + 2] as CompleteFn
      };
    }
    return this.onSnapshotInternal(internalOptions, observer);
  }
 
  private onSnapshotInternal(
    options: ListenOptions,
    observer: PartialObserver<firestore.DocumentSnapshot>
  ): Unsubscribe {
    let errHandler = (err: Error) => {
      console.error('Uncaught Error in onSnapshot:', err);
    };
    if (observer.error) {
      errHandler = observer.error.bind(observer);
    }
 
    const asyncObserver = new AsyncObserver<ViewSnapshot>({
      next: snapshot => {
        Eif (observer.next) {
          assert(
            snapshot.docs.size <= 1,
            'Too many documents returned on a document query'
          );
          const doc = snapshot.docs.get(this._key);
 
          observer.next(
            new DocumentSnapshot(
              this.firestore,
              this._key,
              doc,
              snapshot.fromCache
            )
          );
        }
      },
      error: errHandler
    });
    const internalListener = this._firestoreClient.listen(
      InternalQuery.atPath(this._key.path),
      asyncObserver,
      options
    );
 
    return () => {
      asyncObserver.mute();
      this._firestoreClient.unlisten(internalListener);
    };
  }
 
  get(): Promise<firestore.DocumentSnapshot> {
    validateExactNumberOfArgs('DocumentReference.get', arguments, 0);
    return new Promise(
      (resolve: Resolver<firestore.DocumentSnapshot>, reject: Rejecter) => {
        const unlisten = this.onSnapshotInternal(
          {
            includeQueryMetadataChanges: true,
            includeDocumentMetadataChanges: true,
            waitForSyncWhenOnline: true
          },
          {
            next: (snap: firestore.DocumentSnapshot) => {
              // Remove query first before passing event to user to avoid
              // user actions affecting the now stale query.
              unlisten();
 
              Iif (!snap.exists && snap.metadata.fromCache) {
                // TODO(dimond): If we're online and the document doesn't
                // exist then we resolve with a doc.exists set to false. If
                // we're offline however, we reject the Promise in this
                // case. Two options: 1) Cache the negative response from
                // the server so we can deliver that even when you're
                // offline 2) Actually reject the Promise in the online case
                // if the document doesn't exist.
                reject(
                  new FirestoreError(
                    Code.ABORTED,
                    'Failed to get document because the client is ' + 'offline.'
                  )
                );
              } else {
                resolve(snap);
              }
            },
            error: reject
          }
        );
      }
    );
  }
}
 
class SnapshotMetadata implements firestore.SnapshotMetadata {
  constructor(
    readonly hasPendingWrites: boolean,
    readonly fromCache: boolean
  ) {}
 
  isEqual(other: firestore.SnapshotMetadata): boolean {
    return (
      this.hasPendingWrites === other.hasPendingWrites &&
      this.fromCache === other.fromCache
    );
  }
}
 
/** Options interface that can be provided to configure the deserialization of DocumentSnapshots. */
export interface SnapshotOptions extends firestore.SnapshotOptions {}
 
export class DocumentSnapshot implements firestore.DocumentSnapshot {
  constructor(
    private _firestore: Firestore,
    private _key: DocumentKey,
    public _document: Document | null,
    private _fromCache: boolean
  ) {}
 
  data(
    options?: firestore.SnapshotOptions
  ): firestore.DocumentData | undefined {
    validateBetweenNumberOfArgs('DocumentSnapshot.data', arguments, 0, 1);
    options = validateSnapshotOptions('DocumentSnapshot.data', options);
    return !this._document
      ? undefined
      : this.convertObject(
          this._document.data,
          FieldValueOptions.fromSnapshotOptions(options)
        );
  }
 
  get(
    fieldPath: string | ExternalFieldPath,
    options?: firestore.SnapshotOptions
  ): AnyJs {
    validateBetweenNumberOfArgs('DocumentSnapshot.get', arguments, 1, 2);
    options = validateSnapshotOptions('DocumentSnapshot.get', options);
    if (this._document) {
      const value = this._document.data.field(
        fieldPathFromArgument('DocumentSnapshot.get', fieldPath)
      );
      if (value !== undefined) {
        return this.convertValue(
          value,
          FieldValueOptions.fromSnapshotOptions(options)
        );
      }
    }
    return undefined;
  }
 
  get id(): string {
    return this._key.path.lastSegment();
  }
 
  get ref(): firestore.DocumentReference {
    return new DocumentReference(this._key, this._firestore);
  }
 
  get exists(): boolean {
    return this._document !== null;
  }
 
  get metadata(): firestore.SnapshotMetadata {
    return new SnapshotMetadata(
      this._document !== null && this._document.hasLocalMutations,
      this._fromCache
    );
  }
 
  isEqual(other: firestore.DocumentSnapshot): boolean {
    Iif (!(other instanceof DocumentSnapshot)) {
      throw invalidClassError('isEqual', 'DocumentSnapshot', 1, other);
    }
    return (
      this._firestore === other._firestore &&
      this._fromCache === other._fromCache &&
      this._key.isEqual(other._key) &&
      (this._document === null
        ? other._document === null
        : this._document.isEqual(other._document))
    );
  }
 
  private convertObject(
    data: ObjectValue,
    options: FieldValueOptions
  ): firestore.DocumentData {
    const result: firestore.DocumentData = {};
    data.forEach((key, value) => {
      result[key] = this.convertValue(value, options);
    });
    return result;
  }
 
  private convertValue(value: FieldValue, options: FieldValueOptions): AnyJs {
    if (value instanceof ObjectValue) {
      return this.convertObject(value, options);
    } else if (value instanceof ArrayValue) {
      return this.convertArray(value, options);
    } else if (value instanceof RefValue) {
      const key = value.value(options);
      const database = this._firestore.ensureClientConfigured().databaseId();
      Iif (!value.databaseId.isEqual(database)) {
        // TODO(b/64130202): Somehow support foreign references.
        log.error(
          `Document ${this._key.path} contains a document ` +
            `reference within a different database (` +
            `${value.databaseId.projectId}/${
              value.databaseId.database
            }) which is not ` +
            `supported. It will be treated as a reference in the current ` +
            `database (${database.projectId}/${database.database}) ` +
            `instead.`
        );
      }
      return new DocumentReference(key, this._firestore);
    } else {
      return value.value(options);
    }
  }
 
  private convertArray(data: ArrayValue, options: FieldValueOptions): AnyJs[] {
    return data.internalValue.map(value => {
      return this.convertValue(value, options);
    });
  }
}
 
export class QueryDocumentSnapshot extends DocumentSnapshot
  implements firestore.QueryDocumentSnapshot {
  constructor(
    firestore: Firestore,
    key: DocumentKey,
    document: Document,
    fromCache: boolean
  ) {
    super(firestore, key, document, fromCache);
  }
 
  data(options?: SnapshotOptions): firestore.DocumentData {
    const data = super.data(options);
    assert(
      typeof data === 'object',
      'Document in a QueryDocumentSnapshot should exist'
    );
    return data as firestore.DocumentData;
  }
}
 
export class Query implements firestore.Query {
  constructor(public _query: InternalQuery, readonly firestore: Firestore) {}
 
  where(
    field: string | ExternalFieldPath,
    opStr: firestore.WhereFilterOp,
    value: AnyJs
  ): firestore.Query {
    validateExactNumberOfArgs('Query.where', arguments, 3);
    validateArgType('Query.where', 'string', 2, opStr);
    validateDefined('Query.where', 3, value);
    let fieldValue;
    const fieldPath = fieldPathFromArgument('Query.where', field);
    if (fieldPath.isKeyField()) {
      if (typeof value === 'string') {
        if (value.indexOf('/') !== -1) {
          // TODO(dimond): Allow slashes once ancestor queries are supported
          throw new FirestoreError(
            Code.INVALID_ARGUMENT,
            'Function Query.where() requires its third parameter to be a ' +
              'valid document ID if the first parameter is ' +
              'FieldPath.documentId(), but it contains a slash.'
          );
        }
        if (value === '') {
          throw new FirestoreError(
            Code.INVALID_ARGUMENT,
            'Function Query.where() requires its third parameter to be a ' +
              'valid document ID if the first parameter is ' +
              'FieldPath.documentId(), but it was an empty string.'
          );
        }
        const path = this._query.path.child(new ResourcePath([value]));
        assert(path.length % 2 === 0, 'Path should be a document key');
        fieldValue = new RefValue(
          this.firestore._databaseId,
          new DocumentKey(path)
        );
      } else if (value instanceof DocumentReference) {
        const ref = value as DocumentReference;
        fieldValue = new RefValue(this.firestore._databaseId, ref._key);
      } else {
        throw new FirestoreError(
          Code.INVALID_ARGUMENT,
          `Function Query.where() requires its third parameter to be a ` +
            `string or a DocumentReference if the first parameter is ` +
            `FieldPath.documentId(), but it was: ` +
            `${valueDescription(value)}.`
        );
      }
    } else {
      fieldValue = this.firestore._dataConverter.parseQueryValue(
        'Query.where',
        value
      );
    }
    const filter = fieldFilter(
      fieldPath,
      RelationOp.fromString(opStr),
      fieldValue
    );
    this.validateNewFilter(filter);
    return new Query(this._query.addFilter(filter), this.firestore);
  }
 
  orderBy(
    field: string | ExternalFieldPath,
    directionStr?: firestore.OrderByDirection
  ): firestore.Query {
    validateBetweenNumberOfArgs('Query.orderBy', arguments, 1, 2);
    validateOptionalArgType('Query.orderBy', 'string', 2, directionStr);
    let direction: Direction;
    if (directionStr === undefined || directionStr === 'asc') {
      direction = Direction.ASCENDING;
    } else Eif (directionStr === 'desc') {
      direction = Direction.DESCENDING;
    } else {
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        `Function Query.orderBy() has unknown direction '${directionStr}', ` +
          `expected 'asc' or 'desc'.`
      );
    }
    if (this._query.startAt !== null) {
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        'Invalid query. You must not call Query.startAt() or ' +
          'Query.startAfter() before calling Query.orderBy().'
      );
    }
    if (this._query.endAt !== null) {
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        'Invalid query. You must not call Query.endAt() or ' +
          'Query.endBefore() before calling Query.orderBy().'
      );
    }
    const fieldPath = fieldPathFromArgument('Query.orderBy', field);
    const orderBy = new OrderBy(fieldPath, direction);
    this.validateNewOrderBy(orderBy);
    return new Query(this._query.addOrderBy(orderBy), this.firestore);
  }
 
  limit(n: number): firestore.Query {
    validateExactNumberOfArgs('Query.limit', arguments, 1);
    validateArgType('Query.limit', 'number', 1, n);
    if (n <= 0) {
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        `Invalid Query. Query limit (${n}) is invalid. Limit must be ` +
          'positive.'
      );
    }
    return new Query(this._query.withLimit(n), this.firestore);
  }
 
  startAt(
    docOrField: AnyJs | firestore.DocumentSnapshot,
    ...fields: AnyJs[]
  ): firestore.Query {
    validateAtLeastNumberOfArgs('Query.startAt', arguments, 1);
    const bound = this.boundFromDocOrFields(
      'Query.startAt',
      docOrField,
      fields,
      /*before=*/ true
    );
    return new Query(this._query.withStartAt(bound), this.firestore);
  }
 
  startAfter(
    docOrField: AnyJs | firestore.DocumentSnapshot,
    ...fields: AnyJs[]
  ): firestore.Query {
    validateAtLeastNumberOfArgs('Query.startAfter', arguments, 1);
    const bound = this.boundFromDocOrFields(
      'Query.startAfter',
      docOrField,
      fields,
      /*before=*/ false
    );
    return new Query(this._query.withStartAt(bound), this.firestore);
  }
 
  endBefore(
    docOrField: AnyJs | firestore.DocumentSnapshot,
    ...fields: AnyJs[]
  ): firestore.Query {
    validateAtLeastNumberOfArgs('Query.endBefore', arguments, 1);
    const bound = this.boundFromDocOrFields(
      'Query.endBefore',
      docOrField,
      fields,
      /*before=*/ true
    );
    return new Query(this._query.withEndAt(bound), this.firestore);
  }
 
  endAt(
    docOrField: AnyJs | firestore.DocumentSnapshot,
    ...fields: AnyJs[]
  ): firestore.Query {
    validateAtLeastNumberOfArgs('Query.endAt', arguments, 1);
    const bound = this.boundFromDocOrFields(
      'Query.endAt',
      docOrField,
      fields,
      /*before=*/ false
    );
    return new Query(this._query.withEndAt(bound), this.firestore);
  }
 
  isEqual(other: firestore.Query): boolean {
    Iif (!(other instanceof Query)) {
      throw invalidClassError('isEqual', 'Query', 1, other);
    }
    return (
      this.firestore === other.firestore && this._query.isEqual(other._query)
    );
  }
 
  /** Helper function to create a bound from a document or fields */
  private boundFromDocOrFields(
    methodName: string,
    docOrField: AnyJs | firestore.DocumentSnapshot,
    fields: AnyJs[],
    before: boolean
  ): Bound {
    validateDefined(methodName, 1, docOrField);
    if (docOrField instanceof DocumentSnapshot) {
      Iif (fields.length > 0) {
        throw new FirestoreError(
          Code.INVALID_ARGUMENT,
          `Too many arguments provided to ${methodName}().`
        );
      }
      const snap = docOrField;
      Iif (!snap.exists) {
        throw new FirestoreError(
          Code.NOT_FOUND,
          `Can't use a DocumentSnapshot that doesn't exist for ` +
            `${methodName}().`
        );
      }
      return this.boundFromDocument(methodName, snap._document!, before);
    } else {
      const allFields = [docOrField].concat(fields);
      return this.boundFromFields(methodName, allFields, before);
    }
  }
 
  /**
   * Create a Bound from a query and a document.
   *
   * Note that the Bound will always include the key of the document
   * and so only the provided document will compare equal to the returned
   * position.
   *
   * Will throw if the document does not contain all fields of the order by
   * of the query.
   */
  private boundFromDocument(
    methodName: string,
    doc: Document,
    before: boolean
  ): Bound {
    const components: FieldValue[] = [];
 
    // Because people expect to continue/end a query at the exact document
    // provided, we need to use the implicit sort order rather than the explicit
    // sort order, because it's guaranteed to contain the document key. That way
    // the position becomes unambiguous and the query continues/ends exactly at
    // the provided document. Without the key (by using the explicit sort
    // orders), multiple documents could match the position, yielding duplicate
    // results.
    for (const orderBy of this._query.orderBy) {
      if (orderBy.field.isKeyField()) {
        components.push(new RefValue(this.firestore._databaseId, doc.key));
      } else {
        const value = doc.field(orderBy.field);
        if (value !== undefined) {
          components.push(value);
        } else {
          const field = orderBy.field.canonicalString();
          throw new FirestoreError(
            Code.INVALID_ARGUMENT,
            `Invalid query. You are trying to start or end a query using a ` +
              `document for which the field '${field}' (used as the ` +
              `orderBy) does not exist.`
          );
        }
      }
    }
    return new Bound(components, before);
  }
 
  /**
   * Converts a list of field values to a Bound for the given query.
   */
  private boundFromFields(
    methodName: string,
    values: AnyJs[],
    before: boolean
  ): Bound {
    // Use explicit order by's because it has to match the query the user made
    const orderBy = this._query.explicitOrderBy;
    if (values.length > orderBy.length) {
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        `Too many arguments provided to ${methodName}(). ` +
          `The number of arguments must be less than or equal to the ` +
          `number of Query.orderBy() clauses`
      );
    }
 
    const components: FieldValue[] = [];
    for (let i = 0; i < values.length; i++) {
      const rawValue = values[i];
      const orderByComponent = orderBy[i];
      if (orderByComponent.field.isKeyField()) {
        if (typeof rawValue !== 'string') {
          throw new FirestoreError(
            Code.INVALID_ARGUMENT,
            `Invalid query. Expected a string for document ID in ` +
              `${methodName}(), but got a ${typeof rawValue}`
          );
        }
        if (rawValue.indexOf('/') !== -1) {
          throw new FirestoreError(
            Code.INVALID_ARGUMENT,
            `Invalid query. Document ID '${rawValue}' contains a slash in ` +
              `${methodName}()`
          );
        }
        const key = new DocumentKey(this._query.path.child(rawValue));
        components.push(new RefValue(this.firestore._databaseId, key));
      } else {
        const wrapped = this.firestore._dataConverter.parseQueryValue(
          methodName,
          rawValue
        );
        components.push(wrapped);
      }
    }
 
    return new Bound(components, before);
  }
 
  onSnapshot(observer: PartialObserver<firestore.QuerySnapshot>): Unsubscribe;
  onSnapshot(
    options: firestore.QueryListenOptions,
    observer: PartialObserver<firestore.QuerySnapshot>
  ): Unsubscribe;
  onSnapshot(
    onNext: NextFn<firestore.QuerySnapshot>,
    onError?: ErrorFn,
    onCompletion?: CompleteFn
  ): Unsubscribe;
  onSnapshot(
    options: firestore.QueryListenOptions,
    onNext: NextFn<firestore.QuerySnapshot>,
    onError?: ErrorFn,
    onCompletion?: CompleteFn
  ): Unsubscribe;
 
  onSnapshot(...args: AnyJs[]): Unsubscribe {
    validateBetweenNumberOfArgs('Query.onSnapshot', arguments, 1, 4);
    let options: firestore.QueryListenOptions = {};
    let observer: PartialObserver<firestore.QuerySnapshot>;
    let currArg = 0;
    if (
      typeof args[currArg] === 'object' &&
      !isPartialObserver(args[currArg])
    ) {
      options = args[currArg] as firestore.QueryListenOptions;
      validateOptionNames('Query.onSnapshot', options, [
        'includeQueryMetadataChanges',
        'includeDocumentMetadataChanges'
      ]);
      validateNamedOptionalType(
        'Query.onSnapshot',
        'boolean',
        'includeDocumentMetadataChanges',
        options.includeDocumentMetadataChanges
      );
      validateNamedOptionalType(
        'Query.onSnapshot',
        'boolean',
        'includeQueryMetadataChanges',
        options.includeQueryMetadataChanges
      );
      currArg++;
    }
 
    Iif (isPartialObserver(args[currArg])) {
      observer = args[currArg] as PartialObserver<firestore.QuerySnapshot>;
    } else {
      validateArgType('Query.onSnapshot', 'function', currArg, args[currArg]);
      validateOptionalArgType(
        'Query.onSnapshot',
        'function',
        currArg + 1,
        args[currArg + 1]
      );
      validateOptionalArgType(
        'Query.onSnapshot',
        'function',
        currArg + 2,
        args[currArg + 2]
      );
      observer = {
        next: args[currArg] as NextFn<firestore.QuerySnapshot>,
        error: args[currArg + 1] as ErrorFn,
        complete: args[currArg + 2] as CompleteFn
      };
    }
    return this.onSnapshotInternal(options, observer);
  }
 
  private onSnapshotInternal(
    options: ListenOptions,
    observer: PartialObserver<firestore.QuerySnapshot>
  ): Unsubscribe {
    let errHandler = (err: Error) => {
      console.error('Uncaught Error in onSnapshot:', err);
    };
    if (observer.error) {
      errHandler = observer.error.bind(observer);
    }
 
    const asyncObserver = new AsyncObserver<ViewSnapshot>({
      next: (result: ViewSnapshot): void => {
        Eif (observer.next) {
          observer.next(new QuerySnapshot(this.firestore, this._query, result));
        }
      },
      error: errHandler
    });
 
    const firestoreClient = this.firestore.ensureClientConfigured();
    const internalListener = firestoreClient.listen(
      this._query,
      asyncObserver,
      options
    );
    return () => {
      asyncObserver.mute();
      firestoreClient.unlisten(internalListener);
    };
  }
 
  get(): Promise<firestore.QuerySnapshot> {
    validateExactNumberOfArgs('Query.get', arguments, 0);
    return new Promise(
      (resolve: Resolver<firestore.QuerySnapshot>, reject: Rejecter) => {
        const unlisten = this.onSnapshotInternal(
          {
            includeDocumentMetadataChanges: false,
            includeQueryMetadataChanges: true,
            waitForSyncWhenOnline: true
          },
          {
            next: (result: firestore.QuerySnapshot) => {
              // Remove query first before passing event to user to avoid
              // user actions affecting the now stale query.
              unlisten();
 
              resolve(result);
            },
            error: reject
          }
        );
      }
    );
  }
 
  private validateNewFilter(filter: Filter): void {
    if (filter instanceof RelationFilter && filter.isInequality()) {
      const existingField = this._query.getInequalityFilterField();
      if (existingField !== null && !existingField.isEqual(filter.field)) {
        throw new FirestoreError(
          Code.INVALID_ARGUMENT,
          'Invalid query. All where filters with an inequality' +
            ' (<, <=, >, or >=) must be on the same field. But you have' +
            ` inequality filters on '${existingField.toString()}'` +
            ` and '${filter.field.toString()}'`
        );
      }
 
      const firstOrderByField = this._query.getFirstOrderByField();
      if (firstOrderByField !== null) {
        this.validateOrderByAndInequalityMatch(filter.field, firstOrderByField);
      }
    }
  }
 
  private validateNewOrderBy(orderBy: OrderBy): void {
    if (this._query.getFirstOrderByField() === null) {
      // This is the first order by. It must match any inequality.
      const inequalityField = this._query.getInequalityFilterField();
      if (inequalityField !== null) {
        this.validateOrderByAndInequalityMatch(inequalityField, orderBy.field);
      }
    }
  }
 
  private validateOrderByAndInequalityMatch(
    inequality: FieldPath,
    orderBy: FieldPath
  ): void {
    if (!orderBy.isEqual(inequality)) {
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        `Invalid query. You have a where filter with an inequality ` +
          `(<, <=, >, or >=) on field '${inequality.toString()}' ` +
          `and so you must also use '${inequality.toString()}' ` +
          `as your first Query.orderBy(), but your first Query.orderBy() ` +
          `is on field '${orderBy.toString()}' instead.`
      );
    }
  }
}
 
export class QuerySnapshot implements firestore.QuerySnapshot {
  private _cachedChanges: firestore.DocumentChange[] | null = null;
 
  readonly metadata: firestore.SnapshotMetadata;
 
  constructor(
    private _firestore: Firestore,
    private _originalQuery: InternalQuery,
    private _snapshot: ViewSnapshot
  ) {
    this.metadata = new SnapshotMetadata(
      _snapshot.hasPendingWrites,
      _snapshot.fromCache
    );
  }
 
  get docs(): firestore.QueryDocumentSnapshot[] {
    const result: firestore.QueryDocumentSnapshot[] = [];
    this.forEach(doc => result.push(doc));
    return result;
  }
 
  get empty(): boolean {
    return this._snapshot.docs.isEmpty();
  }
 
  get size(): number {
    return this._snapshot.docs.size;
  }
 
  forEach(
    callback: (result: firestore.QueryDocumentSnapshot) => void,
    thisArg?: AnyJs
  ): void {
    validateBetweenNumberOfArgs('QuerySnapshot.forEach', arguments, 1, 2);
    validateArgType('QuerySnapshot.forEach', 'function', 1, callback);
    this._snapshot.docs.forEach(doc => {
      callback.call(thisArg, this.convertToDocumentImpl(doc));
    });
  }
 
  get query(): firestore.Query {
    return new Query(this._originalQuery, this._firestore);
  }
 
  get docChanges(): firestore.DocumentChange[] {
    if (!this._cachedChanges) {
      this._cachedChanges = changesFromSnapshot(
        this._firestore,
        this._snapshot
      );
    }
    return this._cachedChanges;
  }
 
  /** Check the equality. The call can be very expensive. */
  isEqual(other: firestore.QuerySnapshot): boolean {
    Iif (!(other instanceof QuerySnapshot)) {
      throw invalidClassError('isEqual', 'QuerySnapshot', 1, other);
    }
 
    return (
      this._firestore === other._firestore &&
      this._originalQuery.isEqual(other._originalQuery) &&
      this._snapshot.isEqual(other._snapshot)
    );
  }
 
  private convertToDocumentImpl(doc: Document): QueryDocumentSnapshot {
    return new QueryDocumentSnapshot(
      this._firestore,
      doc.key,
      doc,
      this.metadata.fromCache
    );
  }
}
 
export class CollectionReference extends Query
  implements firestore.CollectionReference {
  constructor(path: ResourcePath, firestore: Firestore) {
    super(InternalQuery.atPath(path), firestore);
    if (path.length % 2 !== 1) {
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        'Invalid collection reference. Collection ' +
          'references must have an odd number of segments, but ' +
          `${path.canonicalString()} has ${path.length}`
      );
    }
  }
 
  get id(): string {
    return this._query.path.lastSegment();
  }
 
  get parent(): firestore.DocumentReference | null {
    const parentPath = this._query.path.popLast();
    if (parentPath.isEmpty()) {
      return null;
    } else {
      return new DocumentReference(new DocumentKey(parentPath), this.firestore);
    }
  }
 
  get path(): string {
    return this._query.path.canonicalString();
  }
 
  doc(pathString?: string): firestore.DocumentReference {
    validateBetweenNumberOfArgs('CollectionReference.doc', arguments, 0, 1);
    // We allow omission of 'pathString' but explicitly prohibit passing in both
    // 'undefined' and 'null'.
    if (arguments.length === 0) {
      pathString = AutoId.newId();
    }
    validateArgType('CollectionReference.doc', 'string', 1, pathString);
    Iif (pathString === '') {
      throw new FirestoreError(
        Code.INVALID_ARGUMENT,
        'Document path must be a non-empty string'
      );
    }
    const path = ResourcePath.fromString(pathString);
    return DocumentReference.forPath(
      this._query.path.child(path),
      this.firestore
    );
  }
 
  add(value: firestore.DocumentData): Promise<firestore.DocumentReference> {
    validateExactNumberOfArgs('CollectionReference.add', arguments, 1);
    validateArgType('CollectionReference.add', 'object', 1, value);
    const docRef = this.doc();
    return docRef.set(value).then(() => docRef);
  }
}
 
function validateSetOptions(
  methodName: string,
  options: firestore.SetOptions | undefined
): firestore.SetOptions {
  if (options === undefined) {
    return {
      merge: false
    };
  }
 
  validateOptionNames(methodName, options, ['merge']);
  validateNamedOptionalType(methodName, 'boolean', 'merge', options.merge);
  return options;
}
 
function validateSnapshotOptions(
  methodName: string,
  options: firestore.SnapshotOptions | undefined
): firestore.SnapshotOptions {
  if (options === undefined) {
    return {};
  }
 
  validateOptionNames(methodName, options, ['serverTimestamps']);
  validateNamedOptionalPropertyEquals(
    methodName,
    'options',
    'serverTimestamps',
    options.serverTimestamps,
    ['estimate', 'previous', 'none']
  );
  return options;
}
 
function validateReference(
  methodName: string,
  documentRef: firestore.DocumentReference,
  firestore: Firestore
): DocumentReference {
  Iif (!(documentRef instanceof DocumentReference)) {
    throw invalidClassError(methodName, 'DocumentReference', 1, documentRef);
  } else if (documentRef.firestore !== firestore) {
    throw new FirestoreError(
      Code.INVALID_ARGUMENT,
      'Provided document reference is from a different Firestore instance.'
    );
  } else {
    return documentRef;
  }
}
 
/**
 * Calculates the array of firestore.DocumentChange's for a given ViewSnapshot.
 *
 * Exported for testing.
 */
export function changesFromSnapshot(
  firestore: Firestore,
  snapshot: ViewSnapshot
): firestore.DocumentChange[] {
  Iif (snapshot.oldDocs.isEmpty()) {
    // Special case the first snapshot because index calculation is easy and
    // fast
    let lastDoc: Document;
    let index = 0;
    return snapshot.docChanges.map(change => {
      const doc = new QueryDocumentSnapshot(
        firestore,
        change.doc.key,
        change.doc,
        snapshot.fromCache
      );
      assert(
        change.type === ChangeType.Added,
        'Invalid event type for first snapshot'
      );
      assert(
        !lastDoc || snapshot.query.docComparator(lastDoc, change.doc) < 0,
        'Got added events in wrong order'
      );
      lastDoc = change.doc;
      return {
        type: 'added' as firestore.DocumentChangeType,
        doc,
        oldIndex: -1,
        newIndex: index++
      };
    });
  } else {
    // A DocumentSet that is updated incrementally as changes are applied to use
    // to lookup the index of a document.
    let indexTracker = snapshot.oldDocs;
    return snapshot.docChanges.map(change => {
      const doc = new QueryDocumentSnapshot(
        firestore,
        change.doc.key,
        change.doc,
        snapshot.fromCache
      );
      let oldIndex = -1;
      let newIndex = -1;
      if (change.type !== ChangeType.Added) {
        oldIndex = indexTracker.indexOf(change.doc.key);
        assert(oldIndex >= 0, 'Index for document not found');
        indexTracker = indexTracker.delete(change.doc.key);
      }
      if (change.type !== ChangeType.Removed) {
        indexTracker = indexTracker.add(change.doc);
        newIndex = indexTracker.indexOf(change.doc.key);
      }
      return { type: resultChangeType(change.type), doc, oldIndex, newIndex };
    });
  }
}
 
function resultChangeType(type: ChangeType): firestore.DocumentChangeType {
  switch (type) {
    case ChangeType.Added:
      return 'added';
    case ChangeType.Modified:
    case ChangeType.Metadata:
      return 'modified';
    case ChangeType.Removed:
      return 'removed';
    default:
      return fail('Unknown change type: ' + type);
  }
}
 
// Export the classes with a private constructor (it will fail if invoked
// at runtime). Note that this still allows instanceof checks.
 
// We're treating the variables as class names, so disable checking for lower
// case variable names.
// tslint:disable:variable-name
export const PublicFirestore = makeConstructorPrivate(
  Firestore,
  'Use firebase.firestore() instead.'
);
export const PublicTransaction = makeConstructorPrivate(
  Transaction,
  'Use firebase.firestore().runTransaction() instead.'
);
export const PublicWriteBatch = makeConstructorPrivate(
  WriteBatch,
  'Use firebase.firestore().batch() instead.'
);
export const PublicDocumentReference = makeConstructorPrivate(
  DocumentReference,
  'Use firebase.firestore().doc() instead.'
);
export const PublicDocumentSnapshot = makeConstructorPrivate(DocumentSnapshot);
export const PublicQueryDocumentSnapshot = makeConstructorPrivate(
  QueryDocumentSnapshot
);
export const PublicQuery = makeConstructorPrivate(Query);
export const PublicQuerySnapshot = makeConstructorPrivate(QuerySnapshot);
export const PublicCollectionReference = makeConstructorPrivate(
  CollectionReference,
  'Use firebase.firestore().collection() instead.'
);
// tslint:enable:variable-name